<?php

namespace App\Services;

use App\Models\Category;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Pagination\LengthAwarePaginator;

class CategoryService
{
    /**
     * 获取分类列表
     */
    public function getCategories(int $perPage = 20): LengthAwarePaginator
    {
        return Category::withCount('dishes')
            ->orderBy('sort_order')
            ->orderBy('created_at', 'desc')
            ->paginate($perPage);
    }

    /**
     * 获取所有分类（不分页）
     */
    public function getAllCategories(): Collection
    {
        return Category::withCount('dishes')
            ->orderBy('sort_order')
            ->get();
    }

    /**
     * 根据ID获取分类
     */
    public function getCategoryById(int $id): Category
    {
        return Category::withCount('dishes')->findOrFail($id);
    }

    /**
     * 创建分类
     */
    public function createCategory(array $data): Category
    {
        return Category::create($data);
    }

    /**
     * 更新分类
     */
    public function updateCategory(int $id, array $data): Category
    {
        $category = Category::findOrFail($id);
        $category->update($data);
        
        return $category->fresh();
    }

    /**
     * 删除分类
     */
    public function deleteCategory(int $id): bool
    {
        $category = Category::findOrFail($id);
        
        // 检查是否有菜品使用此分类
        if ($category->dishes()->count() > 0) {
            throw new \Exception('该分类下还有菜品，无法删除');
        }
        
        return $category->delete();
    }

    /**
     * 切换分类状态
     */
    public function toggleCategoryStatus(int $id): Category
    {
        $category = Category::findOrFail($id);
        $category->is_active = !$category->is_active;
        $category->save();
        
        return $category->fresh();
    }

    /**
     * 搜索分类
     */
    public function searchCategories(string $query, int $perPage = 20): LengthAwarePaginator
    {
        return Category::withCount('dishes')
            ->where('name', 'like', "%{$query}%")
            ->orWhere('description', 'like', "%{$query}%")
            ->orderBy('sort_order')
            ->orderBy('created_at', 'desc')
            ->paginate($perPage);
    }

    /**
     * 按状态筛选分类
     */
    public function getCategoriesByStatus(bool $isActive, int $perPage = 20): LengthAwarePaginator
    {
        return Category::withCount('dishes')
            ->where('is_active', $isActive)
            ->orderBy('sort_order')
            ->orderBy('created_at', 'desc')
            ->paginate($perPage);
    }

    /**
     * 获取分类统计信息
     */
    public function getCategoryStats(): array
    {
        return [
            'total' => Category::count(),
            'active' => Category::where('is_active', true)->count(),
            'inactive' => Category::where('is_active', false)->count(),
            'with_dishes' => Category::has('dishes')->count(),
            'without_dishes' => Category::doesntHave('dishes')->count(),
        ];
    }
}
